<!--
 * @Description: 看板数据源
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 15:11:00
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display: flex">
        <div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0" @click="addFromDate('添加')">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
                  添加
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" size="small" class="bottom_two" @click="UpdateOrDelete('update_status', 0)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                  删除
                </el-button>
              </div>
              <div>
                <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px">
                  <el-link :underline="false">
                    <span class="el-icon--left">
                      <i class="iconfont iconicon_button_filtrate"></i>
                    </span>
                    筛选
                  </el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index) in table" :key="index">
                      <el-checkbox v-model="item.status">{{
                        item.label
                        }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection"></el-table-column>
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :width="item.width">
                    <template slot-scope="scope">
                      <el-button v-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="updateForm(scope.row, '修改')">

                        修改
                      </el-button>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="gettableData()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
        </div>
      </div>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="1180px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div class="dialoginfo">
        <div class="dialogL">
          <div class="dialogL_top">
            <div class="text">SQL语句：</div>
            <div>
              <span>数据限制</span>
              <el-input v-model="fromDate.limitCount" style="width:160px;margin-left:15px;" placeholder="请输入"></el-input>
            </div>
          </div>
          <div class="dialogL_botton">
            <el-input v-model="fromDate.executeSql" type="textarea" :rows="22" resize="none" placeholder=""></el-input>
          </div>
        </div>
        <div class="dialogC">
          <el-button size="small" class="bottom_all" style="margin-left: 0" @click="runSQL()">
            执行
          </el-button>
        </div>
        <div class="dialogR">
          <div class="text">执行结果</div>
          <div class="info table-copy">
            <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="SQLData.dataMapList" tooltip-effect="dark" height="380px">
              <el-table-column v-for="(item2, index2) in fromDate.fieldList" :key="index2" align="center" width="220">
                <template slot="header" slot-scope="scope">
                  <el-input :key="scope.column.id" v-model="item2.customFieldName" style="width:100%" placeholder="输入别名" />
                  <div class="table-title" style="padding-top:10px;">{{item2.fieldName}}</div>
                </template>
                <template slot-scope="scope">
                  <div class="ellipsis">
                    <span>{{ scope.row[item2.fieldName] }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>

          </div>
          <div class="dialogR_botton">
            <el-form ref="reffromDate" :model="fromDate" label-width="110px" :inline="true" style="width: 660px;" :rules="rules">
              <el-form-item label="数据源名称：" prop="dataSourceName">
                <el-input v-model="fromDate.dataSourceName" style="width:160px;" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="所属看板：" prop="functionId">
                <el-select v-model="fromDate.functionId" style="width:160px;" placeholder="请选择">
                  <el-option v-for="(item, index) in functionList" :key="index" :label="item.name" :value="item.functionId"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="pagessubmitFromDate()">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryPage,
  batchUpdateOrDelete,
  saveOrUpdate,
  executor_sql,
  get_detail,
} from "@/api/board/datasource.js";
import { getPerMission } from '@/utils/auth.js';
export default {
  mixins: [mixin],
  data() {
    return {
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      batchUpdateOrDelete: batchUpdateOrDelete,
      saveOrUpdate: saveOrUpdate,
      /*表格数据*/
      table: [
        { label: "数据源名称", width: "auto", prop: "dataSourceName", status: true },
        { label: "归属看板", width: "auto", prop: "functionName", status: true },
        { label: "添加人", width: "auto", prop: "createUserName", status: true },
        { label: "添加时间", width: "auto", prop: "updateTime", status: true },
        { label: "操作", width: "120", prop: "", status: true },
      ],
      pagesType: 0,
      /*添加表单数据*/
      rules: {
        limitCount: [{ required: true, message: "请输入数据源名称", trigger: "blur" }],
        dataSourceName: [{ required: true, message: "请输入数据源名称", trigger: "blur" }],
        functionId: [{ required: true, message: "请选择销售看板", trigger: "change" }],
      },
      fromDate: {
        executeSql: "SELECT * FROM base_system_user ",
        limitCount: 10,
        sourceId: '',
        dataSourceName: '',
        functionName: '',
        functionId: '',
        fieldList: [],
        id: ''
      },
      editFieldList: [],
      isEdit: false,
      functionList: [],
      /**SQL查询结果*/
      SQLData: {},
    };
  },
  created() {
    this.addDialog = false
    this.addDialogTitle = '添加'
    this.gettableData();
    this.getfunction()
  },
  methods: {
    consoleData(scope, data) {
      console.log(scope, data)
    },
    /**权限里获取看板信息*/
    getfunction() {
      this.functionList = getPerMission() ?.functionLimitList.filter(res => (res.code.indexOf('board_Salesofkanban') !== -1))
    },
    /**执行SQL*/
    runSQL() {
      let _this = this
      executor_sql(_this.fromDate).then(res => {
        _this.SQLData = res.data
        let isEdit = !!this.fromDate.id
        let list = []

        if (isEdit) {
          list = _this.editFieldList
          let getItem = false;

          res.data.fieldSet.forEach(res => {
            list.forEach(item => {
              if (item.fieldName === res) {
                item.status = 1;
                getItem = true;
                return
              }
            })

            if (!getItem) {
              list.push({
                customFieldName: '',
                fieldName: res,
                id: '',
                sourceId: '',
                status: 1
              });
            }

            getItem = false
          })

          _this.fromDate.fieldList = list
        } else {
          _this.fromDate.fieldList = res.data.fieldSet.map(res => {
            return {
              customFieldName: '',
              fieldName: res,
              id: '',
              sourceId: '',
              status: 1
            }
            // return new field('', res, '', '', 1)
          })
        }

        console.log(_this.fromDate)
      })
    },
    /*重置数据*/
    init() {
      this.tableParam.name = "";
      this.tableParam.code = "";
      this.gettableData();
    },
    /**
     * 更新数据源
     * @param  {object} row   数据源对象
     * @param  {string} title 对话框名称
     * @return {[type]}       [description]
     */
    updateForm(row, title) {
      this.updateFromDate(row, title);
      get_detail({ id: row.id }).then(res => {
        res.data.fieldList.map(res => {
          res.status = 0
        })
        this.editFieldList = res.data.fieldList;
        this.runSQL();
      })
    },
    /*保存数据*/
    pagessubmitFromDate() {
      let _this = this;
      _this.$refs.reffromDate.validate((valid) => {
        if (valid) {
          _this.fromDate.functionName = getPerMission() ?.functionLimitList.find((res) => (res.functionId == _this.fromDate.functionId)).name
          console.log(_this.fromDate)
          if (!_this.fromDate.executeSql) {
            this.$message({
              message: '警告哦，请先输入SQL语句！！！',
              type: 'warning'
            });
          }
          _this.submitFromDate();
        } else {
          return false;
        }
      });
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.gettableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-input,
.el-select {
  width: 240px;
}
/*
 <el-link class="table_link" :underline="false">查看配合比</el-link>*/
.table_link {
  margin: 0 10px;
  color: $bg_color;
  cursor: pointer;
}

.table_link:hover {
  opacity: 0.8;
}
.dialoginfo {
  display: flex;
  height: 500px;
  padding: 0;
  .text {
    font-weight: bold;
  }
  .dialogL {
    width: 340px;
    .dialogL_top {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .dialogL_botton {
      padding-top: 15px;
    }
  }
  .dialogC {
    width: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .dialogR {
    flex: 1;
    .text {
      line-height: 36px;
    }
    .info {
      margin-top: 15px;
      height: calc(100% - 110px);
      width: 680px;
    }
    .dialogR_botton {
      padding-top: 15px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}
</style>
